package com.avic.rong.activity.mine;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.opengl.ETC1;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.pickerview.OptionsPickerView;
import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.api.mine.GetDetailInfoApi;
import com.avic.rong.api.mine.UpDetailInfoApi;
import com.avic.rong.bean.mine.Bean;
import com.avic.rong.bean.mine.DetailInfoBean;
import com.avic.rong.userOrder.bean.AddressListBean;
import com.avic.rong.userOrder.bean.ZipCodeBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.StringUtil;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.luck.picture.lib.dialog.CustomDialog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

public class DetailInfoActivity extends BaseActivity {

    @BindView(R.id.edittext_name)
    EditText edittext_name;
    @BindView(R.id.edittext_xxmsg)
    EditText edittext_xxmsg;
    @BindView(R.id.btn_exit)
    Button btn_exit;
    @BindView(R.id.rl_AddressSelect)
    RelativeLayout rl_AddressSelect;
    @BindView(R.id.tv_add_address)
    TextView tv_add_address;
    private OptionsPickerView<String> mOpv;
    private JSONObject mJsonObj;

    // 省数据集合
    private ArrayList<String> mListProvince = new ArrayList<String>();
    private ArrayList<ZipCodeBean> mListProvinceBean = new ArrayList<>();
    // 市数据集合
    private ArrayList<ArrayList<String>> mListCity = new ArrayList<ArrayList<String>>();
    private ArrayList<ArrayList<ZipCodeBean>> mListCityBean = new ArrayList<ArrayList<ZipCodeBean>>();
    // 区数据集合
    private ArrayList<ArrayList<ArrayList<String>>> mListArea = new ArrayList<ArrayList<ArrayList<String>>>();
    private ArrayList<ArrayList<ArrayList<ZipCodeBean>>> mListAreaBean = new ArrayList<ArrayList<ArrayList<ZipCodeBean>>>();
    private int address;
    private AddressListBean address_bean;

    private String belongProvince;
    private String belongProvinceZipcode;
    private String belongCity;
    private String belongCityZipcode;
    private String login_token;
    private String companyName;
    private String add_address;
    private String xxMsg;
    private String oldaddress;
    private String oldcompanyName;
    private String oldcompanyAddress;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_detail_info;
    }

    @Override
    protected void initView() {
        tvTitle.setText("修改详细信息");
        ivRight.setBackgroundResource(R.mipmap.slh);

        login_token = SharedPreferencesUtil.getInstance().getAsString("login_token", null);


        GetDetailInfoApi getDetailInfoApi = new GetDetailInfoApi(this, getDetailInfoListener);
        getDetailInfoApi.setToken(login_token);
        HttpManager.getInstance().doHttpDeal(getDetailInfoApi);

    }

    //详细地址
    HttpOnNextListener<BaseResultEntity> getDetailInfoListener = new HttpOnNextListener<BaseResultEntity>() {

        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){
                DetailInfoBean data = (DetailInfoBean) baseResultEntity.getData();
                if (data!=null) {
                    oldaddress = data.getAddress();
                    oldcompanyName = data.getCompanyName();
                    oldcompanyAddress = data.getCompanyAddress();
                    if (!StringUtil.isEmpty(oldaddress)) {
                        edittext_xxmsg.setText(oldaddress);//详细地址
                    }else {
                        oldaddress = "";
                    }

                    if (!StringUtil.isEmpty(oldcompanyName)) {
                        edittext_name.setText(oldcompanyName);//公司名称
                    }else {
                        oldcompanyName = "";
                    }

                    if (!StringUtil.isEmpty(oldcompanyAddress)) {
                        tv_add_address.setText(oldcompanyAddress);//所在地区
                    }else {
                        oldcompanyAddress = "";
                    }
                }
            }
        }
    };

    @Override
    protected void addListener() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = edittext_name.getText().toString().trim();
                String xxMsg = edittext_xxmsg.getText().toString().trim();
                String tvAddress = tv_add_address.getText().toString().trim();

                if (name.equals(oldcompanyName)&&xxMsg.equals(oldaddress)&&tvAddress.equals(oldcompanyAddress)){
                    finish();
                }else {
                    showDialog();
                }
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(this,Objects.requireNonNull(v).getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }
   // 判断点击的区域是否需要关闭软键盘
    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     */
    public static boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            //得到输入框在屏幕中上下左右的位置
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
            // 点击位置如果是EditText的区域，忽略它，不收起键盘。
                return false;
            }
            else {
                return true;
            }
        }
        return false;
    }
    //关闭软键盘
    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    public static void hideKeyboard(Activity activity, IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            Objects.requireNonNull(im).hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void showDialog() {
        CustomDialog dialog = new CustomDialog(this, R.layout.dialog_upname);
        dialog.show();
        dialog.setCanceledOnTouchOutside(false);
        dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });



        dialog.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, DetailInfoActivity.class);
        return intent;
    }

    @OnClick({ R.id.btn_exit, R.id.rl_AddressSelect})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_exit:
                commit();
                break;
            case R.id.rl_AddressSelect:
                addressSelect();
                break;
        }
    }

    //提交地址
    private void commit() {
        add_address = tv_add_address.getText().toString().trim();
        xxMsg = edittext_xxmsg.getText().toString().trim();
        companyName = edittext_name.getText().toString().trim();

        if (StringUtil.isEmpty(add_address)||StringUtil.isEmpty(xxMsg)||StringUtil.isEmpty(companyName)){
            ToastTools.showPublicToast("内容不能为空");
        }else {
            UpDetailInfoApi upDetailInfoApi = new UpDetailInfoApi(this, upDetailInfoListener);
            upDetailInfoApi.setArgument(login_token, belongProvinceZipcode, belongCityZipcode, belongProvince, belongCity, companyName, xxMsg);
            HttpManager.getInstance().doHttpDeal(upDetailInfoApi);
        }


    }

    HttpOnNextListener<BaseResultEntity> upDetailInfoListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){
                EventBus.getDefault().post(new Bean(companyName,add_address,xxMsg));
                finish();
            }else {
                Toast.makeText(DetailInfoActivity.this, baseResultEntity.getMsg(), Toast.LENGTH_SHORT).show();
            }
        }
    };
    //地区选择
    private void addressSelect() {
        // 初始化Json对象
        initJsonData();
        // 初始化Json数据
        initJsonDatas();
        // 创建选项选择器对象
        mOpv = new OptionsPickerView<>(DetailInfoActivity.this);
        // 设置标题
        mOpv.setTitle("选择城市");
        // 设置三级联动效果
        mOpv.setPicker(mListProvince, mListCity, mListArea, true);
        // 设置是否循环滚动
        mOpv.setCyclic(false, false, false);
        // 设置默认选中的三级项目
        mOpv.setSelectOptions(0, 0, 0);
        // 监听确定选择按钮
        mOpv.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                // 返回的分别是三个级别的选中位置
                String addressStr = mListProvinceBean.get(options1).getName();
                belongProvince = mListProvinceBean.get(options1).getName();
                belongCity = mListCityBean.get(options1).get(option2).getName();
                belongProvinceZipcode = mListProvinceBean.get(options1).getZipcode();
                belongCityZipcode = mListCityBean.get(options1).get(option2).getZipcode();
                tv_add_address.setText(belongProvince + belongCity);
            }
        });
        mOpv.show();
    }

    /**
     * 从assert文件夹中读取省市区的json文件，然后转化为json对象
     */
    private void initJsonData() {
        try {
            StringBuffer sb = new StringBuffer();
            InputStream is = getAssets().open("city.json");
            int len = -1;
            byte[] buf = new byte[2048];
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "UTF-8"));
            }
            is.close();
            mJsonObj = new JSONObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化Json数据，并释放Json对象
     */
    private void initJsonDatas() {
        try {
            JSONObject rootObj = mJsonObj.optJSONObject("root");
            JSONArray jsonArray = rootObj.optJSONArray("province");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 获取每个省的Json对象
                String province = jsonP.optString("name");
                ZipCodeBean provinceBean = new ZipCodeBean(jsonP.optString("name"), jsonP.optString("zipcode"));

                ArrayList<String> options2Items_01 = new ArrayList<String>();
                ArrayList<ArrayList<String>> options3Items_01 = new ArrayList<ArrayList<String>>();
                ArrayList<ZipCodeBean> options2Items_01_bean = new ArrayList<ZipCodeBean>();
                ArrayList<ArrayList<ZipCodeBean>> options3Items_01_bean = new ArrayList<ArrayList<ZipCodeBean>>();
                JSONArray jsonCs = jsonP.getJSONArray("city");
                for (int j = 0; j < jsonCs.length(); j++) {
                    JSONObject jsonC = jsonCs.getJSONObject(j);// 获取每个市的Json对象
                    String city = jsonC.optString("name");
                    ZipCodeBean cityBean = new ZipCodeBean(jsonC.optString("name"), jsonC.optString("zipcode"));
                    options2Items_01.add(city);// 添加市数据
                    options2Items_01_bean.add(cityBean);

                    ArrayList<String> options3Items_01_01 = new ArrayList<String>();
                    ArrayList<ZipCodeBean> options3Items_01_01_bean = new ArrayList<ZipCodeBean>();
                    JSONArray jsonAs = jsonC.optJSONArray("district");
                    if (jsonAs != null) {
                        for (int k = 0; k < jsonAs.length(); k++) {
                            JSONObject distObj = jsonAs.getJSONObject(k);
                            String district = distObj.optString("name");
                            ZipCodeBean districtBean = new ZipCodeBean(distObj.optString("name"), distObj.optString("zipcode"));
                            options3Items_01_01.add(district);// 添加区数据
                            options3Items_01_01_bean.add(districtBean);
                        }
                    }
                    options3Items_01.add(options3Items_01_01);
                    options3Items_01_bean.add(options3Items_01_01_bean);
                }
                mListProvince.add(province);// 添加省数据
                mListCity.add(options2Items_01);
                mListArea.add(options3Items_01);

                mListProvinceBean.add(provinceBean);
                mListCityBean.add(options2Items_01_bean);
                mListAreaBean.add(options3Items_01_bean);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mJsonObj = null;
    }

}
